using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model.Core.DbContexts;
using Model.Core.Entity.Robots;
using RobotWebApiService.Models;
using RobotWebApiService.Models;
using Swashbuckle.AspNetCore.Annotations;

namespace RobotWebApiService.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RobotInfoController : ControllerBase
    {
        private readonly MyDbContext _context;
        private readonly ILogger _logger;

        public RobotInfoController(MyDbContext context,ILogger logger)
        {
            _context = context;
            this._logger = logger;
        }

        [HttpGet]
        [SwaggerOperation("获取所有机器人信息")]
        public async Task<ApiResponse<IEnumerable<RobotInfo>>> GetAsync()
        {
            try
            {
                return new ApiResponse<IEnumerable<RobotInfo>>(true, "", _context.RobotInfo.ToList());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "RobotInfo控制器操作异常");
                return new ApiResponse<IEnumerable<RobotInfo>>(false, ex.Message);
            }
        }

        [HttpPost]
        public ApiResponse<RobotInfo> Post([FromBody] RobotInfo entity)
        {
            try
            {
                if (!ModelState.IsValid)
                    return new ApiResponse<RobotInfo>(false, "无效的请求数据");

                _context.RobotInfo.Add(entity);
                _context.SaveChanges();
                return new ApiResponse<RobotInfo>(true, "创建成功", entity);
            }
            catch (Exception ex)
            {
                return new ApiResponse<RobotInfo>(false, ex.Message);
            }
        }

        [HttpPut("{id}")]
        public ApiResponse<RobotInfo> Put(string id, [FromBody] RobotInfo entity)
        {
            try
            {
                if (Guid.Parse(id) != entity.Id)
                    return new ApiResponse<RobotInfo>(false, "ID不匹配");

                _context.Entry(entity).State = EntityState.Modified;
                _context.SaveChanges();
                return new ApiResponse<RobotInfo>(true, "更新成功", entity);
            }
            catch (Exception ex)
            {
                return new ApiResponse<RobotInfo>(false, ex.Message);
            }
        }

        [HttpDelete("{id}")]
        public ApiResponse<string> Delete(string id)
        {
            try
            {
                var entity = _context.RobotInfo.Find(id);
                if (entity == null)
                    return new ApiResponse<string>(false, "未找到该记录");

                _context.RobotInfo.Remove(entity);
                _context.SaveChanges();
                return new ApiResponse<string>(true, "删除成功");
            }
            catch (Exception ex)
            {
                return new ApiResponse<string>(false, ex.Message);
            }
        }
    }
}